/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 保管费发放页面
 *  */

import React, { useState } from 'react';
import { useAntdTable, useDebounceFn } from 'ahooks';
import StandardTable from '@/components/StandardTable';
import { Button, Form, DatePicker, message } from 'antd';
// eslint-disable-next-line import/no-extraneous-dependencies
import { useDispatch } from 'dva';
import Yzs from '@/components/Select/Yzs';
import moment from 'moment';
import FeeDistributeModal from './FeeDistributeModal';

const { MonthPicker } = DatePicker;

const FormItem = Form.Item;

const StorageFeeDistribution = ({ form }) => {
  const { getFieldDecorator } = form;
  const dispatch = useDispatch();
  const [selectedRows, setSelectedRows] = useState([]);
  const [totalFeeInfo, setTotalFeeInfo] = useState({
    fee_decrease_sum: 0,
    fee_wait_sum: 0,
    fee_already_sum: 0,
  });
  const [modalType, setModalType] = useState('distribution');
  const [visible, setVisible] = useState(false);
  const [recordValue, setRecordValue] = useState({});
  const [feeWait, setFeeWait] = useState(0);

  const getTableList = async ({ current }, formData) => {
    console.log('formData', formData);
    const { month, ...rest } = formData;
    const { list, pagination, summery } = await dispatch({
      type: 'dispat/getDistributionList',
      payload: {
        month: month ? month.format('YYYY-MM') : undefined,
        ...rest,
        page: current,
      },
    });
    setTotalFeeInfo(summery);
    setFeeWait();
    setRecordValue();
    setModalType();
    setSelectedRows([]);
    const newList = list.map(i => {
      if (i.send_status === '2') {
        i.disabled = true;
      } else {
        i.disabled = false;
      }
      return i;
    });
    return {
      total: pagination.total,
      list: newList,
    };
  };

  const { search, loading, tableProps, refresh: tableRefresh } = useAntdTable(getTableList, {
    defaultPageSize: 10,
    form,
  });

  const { run: submit } = useDebounceFn(
    () => {
      search.submit();
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const onDispatch = data => {
    const handleType = data.id ? 'distribution' : 'giveOutBanch';
    setFeeWait(
      handleType === 'distribution'
        ? data.fee_wait
        : selectedRows
            .map(i => i.fee_wait)
            .reduce((prev, curn) => (prev * 1 + curn * 1).toFixed(2)),
    );
    setModalType(handleType);
    setRecordValue(handleType === 'distribution' ? data : {});
    setVisible(true);
  };

  const columns = summery => [
    {
      title: '入库时间',
      dataIndex: 'send_month',
      key: 'send_month',
    },
    {
      title: '驿站名称',
      dataIndex: 'yz_name',
      key: 'id',
    },
    {
      title: `应发金额（${summery.fee_wait_sum || ''}元）`,
      dataIndex: 'fee_wait',
      key: 'fee_wait',
      render: text => <span style={{ color: 'red' }}>{text}</span>,
    },
    {
      title: `已发放金额（${summery.fee_already_sum || ''}元）`,
      dataIndex: 'fee_already',
      key: 'fee_already',
    },
    {
      title: `核减金额（${summery.fee_decrease_sum || ''}元）`,
      dataIndex: 'fee_decrease',
      key: 'fee_decrease',
    },
    {
      dataIndex: 'send_status',
      render: (send_status, record) => {
        if (send_status === '1') {
          return (
            // eslint-disable-next-line react/jsx-no-bind
            <Button type="primary" onClick={onDispatch.bind(null, record)}>
              发放
            </Button>
          );
        }
        return '已发放';
      },
    },
  ];

  const onRowSelect = selectList => {
    setModalType(selectList.length ? 'giveOutBanch' : 'distribution');
    setSelectedRows(selectList);
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const handleOk = values => {
    const { deductFee, sendFee } = values || {};
    const paramsList = modalType === 'distribution' ? [recordValue] : selectedRows;
    const params = {
      send_ids: paramsList.map(item => item.id).toString(),
      send_cm_id: paramsList.map(item => item.cm_id).toString(),
      deduct_fee: deductFee || '',
      send_fee: modalType === 'distribution' ? sendFee || '' : feeWait,
    };
    dispatch({
      type: 'dispat/storageFeeRelease',
      payload: { ...params },
    }).then(({ code, msg }) => {
      if (code === 0) {
        message.success('发放成功');
        setVisible(false);
        tableRefresh();
        onRowSelect([]);
      } else {
        message.error(msg);
        setVisible(false);
      }
    });
  };

  const disabledDate = current => !(current && current <= moment());

  return (
    <div>
      <Form layout="inline">
        <FormItem>
          {getFieldDecorator('month', {
            // initialValue: moment(),
          })(<MonthPicker disabledDate={disabledDate} />)}
        </FormItem>
        <FormItem>
          {getFieldDecorator('cm_id', {
            initialValue: 'all',
          })(<Yzs />)}
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={submit}>
            查询
          </Button>
        </FormItem>
        <FormItem>
          <Button type="primary" disabled={selectedRows.length === 0} onClick={onDispatch}>
            批量发放
          </Button>
        </FormItem>
      </Form>
      <StandardTable
        scroll={{ x: 900 }}
        loading={loading}
        rowKey="id"
        selectedRows={selectedRows}
        onSelectRow={onRowSelect}
        data={{
          list: tableProps.dataSource,
          pagination: {
            ...tableProps.pagination,
            showQuickJumper: false,
            showSizeChanger: false,
          },
        }}
        columns={columns(totalFeeInfo)}
        onChange={tableProps.onChange}
      />
      <FeeDistributeModal
        form={form}
        onCancel={handleCancel}
        onOk={handleOk}
        type={modalType}
        visible={visible}
        recordValue={recordValue}
        selectedRows={selectedRows}
        feeWait={feeWait}
      />
    </div>
  );
};

export default Form.create()(StorageFeeDistribution);
